<?php
/*
 * @Description: 短信类
 * @Author: QianLong
 * @Date: 2019-09-27 16:34:02
 * @LastEditors    : QianLong
 * @LastEditTime   : 2021-04-27 14:46:41
 */

namespace app\common\service;

use app\lib\exception\ApiException;
use OSS\Core\OssException;
use think\facade\Db;
use OSS\OssClient;

class AliOss
{
    protected $ossClient;
    protected $ossConfig;
    public function __construct()
    {
        //获取配置项，并赋值给对象$this->ossConfig
        if (!$this->ossConfig) {
            $this->ossConfig = Db::name('SysAliossSetting')->where('id', 1)->find();
        }
        if ($this->ossConfig['is_internal_upload'] == 1) {
            $this->ossConfig['Endpoint'] = $this->ossConfig['region'].'-internal.aliyuncs.com';
        }else{
            $this->ossConfig['Endpoint'] = $this->ossConfig['region'].'.aliyuncs.com';
        }
        //实例化OSS
        if ($this->ossConfig['open'] == 1) {
            $this->ossClient = new OssClient($this->ossConfig['key_id'], $this->ossConfig['key_secret'], $this->ossConfig['Endpoint']);
        }
    }
    public function getConfig()
    {
        return $this->ossConfig;
    }
    public function uploadFile($object, $Path)
    {
        //try 要执行的代码,如果代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示
        try {
            if (is_null($this->ossClient)) {
                exit(1);
            }
            //uploadFile的上传方法
            $oss_data = $this->ossClient->uploadFile($this->ossConfig['bucket'], $object, $Path);
            return $oss_data;
        } catch (OssException $e) {
            throw new ApiException($e->getMessage());
        }
        //否则，完成上传操作
        return true;
    }
    public function getOssSecureUrl($object, $timeout = 60)
    {
        if (is_null($this->ossClient)) {
            exit(1);
        }
        try {
            $signedUrl = $this->ossClient->signUrl($this->ossConfig['bucket'], $object, $timeout);
        } catch (OssException $e) {
            throw new ApiException($e->getMessage());
        }
        if (strpos($signedUrl, 'http://') === 0) {
            $table_change = array('http://' => 'https://');
            $signedUrl = strtr($signedUrl, $table_change);
        }
        $signedUrl = str_replace('-internal', '', $signedUrl);
        return $signedUrl;
    }
    public function getOssUrl($object)
    {
        if ($this->ossConfig['is_define_url'] == 1) {
            $url = $this->ossConfig['web_url'];
        }else{
            $url = 'https://'.$this->ossConfig['bucket'].'.'.$this->ossConfig['region'].'.aliyuncs.com';
        }
        $url = rtrim($url,'/');
        return $url .'/'. $object;
    }
    public function deleteOssFile($object)
    {
        if (is_null($this->ossClient)) {
            exit(1);
        }
        try {
            $signedUrl = $this->ossClient->deleteObject($this->ossConfig['bucket'], $object);
            return $signedUrl;
        } catch (OssException $e) {
            throw new ApiException($e->getMessage());
        }
    }
}
